<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Logic;


use App\Common\HttpClient;
use App\Common\Logger;
use App\Common\Tool;
use App\Exceptions\ApiException;
use App\Model\Room\CreateRoomRec;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class RoomRecLogic extends Logic
{

    /**
     * 查看当前拥有房卡是否满足开房
     * @param $uid
     * @param $use_cards
     * @throws ApiException
     */
//    public function checkRoomTicket($uid, $use_cards)
//    {
//        if (!DB::table('t_player_info')->where('id', $uid)->where('room_ticket', '>', $use_cards)->value('id')) {
//            throw new ApiException('当前房卡数量不够', 1);
//        }
//    }


    /**
     * 创建房间
     * @param $param
     * @param $uid
     * @param $number
     * @return int|array
     * @throws ApiException
     */
    public function createRoom($param, $uid, $rand_room)
    {
//        if ($param['use_cards'] == 1) {
//            $board_choose = 3;
//        }elseif ($param['use_cards'] == 2) {
//            $board_choose = 6;
//        } else {
//            throw new ApiException('开房房卡数量错误');
//        }
        $data = [
            'uid' => $uid,
            'player_num' => $param['player_num'],
            'board_choose' => $param['board_choose'],
            'use_cards' => 0,
            'password' => (int)$rand_room,
            'rule' => '贵阳麻将|冲锋鸡',
            'create_time' => date('Y-m-d H:i:s')
        ];
        //如果有俱乐部id则插入
        if (!empty($param['club_id'])) {
            $data['clubid'] = $param['club_id'];
            $room_id        = DB::table('t_create_room_rec')->insertGetId($data);
        } else {
            $object = DB::table('t_create_room_rec')->where('clubid',0)->where('uid',$uid)->where('status',1)->first();
            if (!empty($object)) {
                //如果普通房间还存在,直接返回，不继续创建
                return [
                    'room_info' => [
                        'room_id' => $object->id,
                        'uid' => $uid,
                        'room_pwd' => $object->password,
                        'board' => $object->board_choose,
                        'cost_ticket' => 0
                    ]
                ];
            }
            $room_id = DB::table('t_create_room_rec')->insertGetId($data);
        }
        return $room_id;
    }


    /**
     * 激活房间
     * @param $id
     * @param $uid
     * @return mixed
     * @throws ApiException
     */
    public function action($id, $uid)
    {
        if (DB::table('t_create_room_rec')
            ->where('id', $id)
            ->where('uid', $uid)
            ->where('status', 0)
            ->update(['status' => 1])
        ) {
            return true;
        }
        throw new ApiException('action room failure', 2);
    }


    /**
     * 扣除个人房卡
     * @param $uid
     * @param $use_cards
     * @return
     * @throws ApiException
     */
    public function reduce($uid, $use_cards, $id)
    {
        $data                = array();
        $url                 = env('MIGU_BASE_URL') . '/deductRoomCards';
        $data['timestamp']   = (string)Tool::msectime();
        $data['userId']      = Tool::getMiGuId($uid);
        $data['quantity']    = (int)$use_cards;
        $data['orderId']     = $this->orderno($uid);
        $data['gameId']      = MiGuLogic::$gameID;
        $data['propId']      = 110000;
        $data['clientId']    = MiGuLogic::$client_id;
        $data['clientIdSub'] = MiGuLogic::$client_sub;
        $data['version']     = MiGuLogic::$version;
        $data['signature']   = Tool::miGuSignature($data);
        $client              = new HttpClient();
        $ret                 = $client->MiGuPost($url, json_encode($data));
        if (empty($ret)) {
            throw new ApiException('请求扣除房卡失败', 6);
        }
        $ret = json_decode($ret, true);
        if ($ret['returnCode'] != '000000') {
            throw new ApiException($ret['returnCode'] . ':' . $ret['resultData']['message'], -500);
        }
        DB::table('t_create_room_rec')->where('id',$id)->update(['order_id' => $data['orderId']]);
        return $ret['resultData']['result'];
    }


    /**
     * 解散房间
     * @param $id
     * @param $uid
     * @return
     * @throws ApiException
     */
    public function dissolutionLogic($id, $uid)
    {
        if (!empty(Redis::hGet('ROOM_PLAYER_NUM', $id))) {
            throw new ApiException('房间有人不能解散', 6);
        }
        $object = CreateRoomRec::where('id', $id)
            ->where('uid', $uid)
            ->where('service_id', 0)
            ->where('desk_id', 0)
            ->where('status', '<', 3)
            ->first(['id','order_id','password']);
        if (empty($object)) {
            throw new ApiException('当前房间状态不能解散', 6);
        }
        $data                = [];
        $url                 = env('MIGU_BASE_URL') . '/returnRoomCards';
        $data['timestamp']   = (string)Tool::msectime();
        $data['userId']      = Tool::getMiGuId($uid);
        $data['gameId']      = MiGuLogic::$gameID;
        $data['orderId']     = $object->order_id;
        $data['propId']      = 110000;
        $data['clientId']    = MiGuLogic::$client_id;
        $data['clientIdSub'] = MiGuLogic::$client_sub;
        $data['version']     = MiGuLogic::$version;
        $data['signature']   = Tool::miGuSignature($data);
        $client              = new HttpClient();
        $ret                 = $client->MiGuPost($url, json_encode($data));
        if (empty($ret)) {
            throw new ApiException('请求退还房间失败', 6);
        }
        $ret = json_decode($ret, true);
        if ($ret['returnCode'] != '000000') {
            throw new ApiException($ret['returnCode'] . ':' . $ret['message'], -500);
        }
        //更新房间状态
        $object->status = 4;
        $object->save();
        Redis::eval(file_get_contents(base_path().'/redisscript/return_room.lua'),2,env('REDIS_ROOM_KEY'),$object->password);
        return $ret['resultData'];
    }


    private function orderno($uid)
    {
        return microtime(true) * 10000 .'u' . $uid .mt_rand(10000,99999);
    }


}